package com.aliyun.dingtalk.controller;

import com.aliyun.dingtalk.service.AttendanceCacheService;
import com.aliyun.dingtalk.service.DingTalkUserService;
import com.aliyun.dingtalk.model.ServiceResult;
import com.aliyun.dingtalk.service.UserCacheService;
import com.aliyun.dingtalk.service.impl.AttendanceCacheServiceImpl;
import com.aliyun.dingtalk.service.impl.UserCacheServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 钉钉h5企业内部应用DEMO, 实现了根据用户授权码获取用户信息功能
 */
@RestController
public class DingTalkUserController {

    @Autowired
    private DingTalkUserService dingTalkUserService;

    @Autowired
    private AttendanceCacheService attendanceCacheService;

    @Autowired
    private UserCacheService userCacheService;


    /**
     * 欢迎页面, 检查后端服务是否启动
     *
     * @return
     */
    @GetMapping("/welcome")
    public String welcome() {
        return "welcome";
    }

    /**
     * 根据免登授权码, 获取登录用户身份
     *
     * @param authCode 免登授权码
     * @return
     */
    @GetMapping("/login")
    public ServiceResult login(@RequestParam(value = "authCode") String authCode) {

        return ServiceResult.getSuccessResult(dingTalkUserService.getUserInfo(authCode));

    }

    /**
     * 首先需要通过企业的corpId和corpSecret获取访问令牌

     */
    @GetMapping("/getAccessToken")
    public Object getAccessToken() {
        return ServiceResult.getSuccessResult(dingTalkUserService.getAccessToken());
    }

    /**
     * 获取部门列表
     */
    @GetMapping("/getDeptList")
    public Object getDeptList() {
        return ServiceResult.getSuccessResult(dingTalkUserService.getDeptList());
    }


    /**
     * 通过部门ID查询部门下所有人员信息
     */
    @GetMapping("/getUserListByDeptId")
    public Object getUserListByDeptId(@RequestParam(value = "deptId") Long deptId) {
        return ServiceResult.getSuccessResult(dingTalkUserService.getUserListByDeptId(deptId));
    }


    /**
     * 获取部门列表及各部门下的用户列表
     */
    @GetMapping("/getDeptListWithUsers")
    public Object getDeptListWithUsers() {
        return ServiceResult.getSuccessResult(dingTalkUserService.getDeptListWithUsers());
    }


    /**
     * 获取所有用户及其详细信息（优化版）
     */
    @GetMapping("/getAllUsersWithDetails")
    public Object getAllUsersWithDetails() {
        return ServiceResult.getSuccessResult(dingTalkUserService.getAllUsersWithDetails());
    }


    // 在 DingTalkUserController 类中添加以下方法
    /**
     * 通过用户ID获取用户详情
     */
    @GetMapping("/getUserDetail")
    public Object getUserDetail(@RequestParam(value = "userId") String userId) {
        return ServiceResult.getSuccessResult(dingTalkUserService.getUserDetail(userId));
    }





    /**
     * 手动触发同步所有用户详细信息到Redis
     */
    @GetMapping("/manualSyncUsers")
    public Object manualSyncUsers() {
        try {
            userCacheService.manualSyncAllUsersToCache();
            return ServiceResult.getSuccessResult("用户数据手动同步成功");
        } catch (Exception e) {
            return ServiceResult.getFailureResult("500", "用户数据手动同步失败: " + e.getMessage());
        }
    }

    /**
     * 手动触发更新考勤数据缓存
     */
    @GetMapping("/manualCacheAttendance")
    public Object manualCacheAttendance() {
        try {
            attendanceCacheService.manualCacheAttendanceData();
            return ServiceResult.getSuccessResult("考勤数据手动缓存成功");
        } catch (Exception e) {
            return ServiceResult.getFailureResult("500", "考勤数据手动缓存失败: " + e.getMessage());
        }
    }




    /**
     * 获取缓存的所有用户详细信息
     */
    @GetMapping("/getAllUsersWithDetailsFromCache")
    public Object getAllUsersWithDetailsFromCache() {
        Object cachedData = dingTalkUserService.getAllUsersWithDetailsFromCache();
        if (cachedData != null) {
            return ServiceResult.getSuccessResult(cachedData);
        } else {
            return ServiceResult.getFailureResult("404", "暂无缓存数据");
        }
    }

    /**
     * 获取缓存的考勤数据（按时间范围筛选）
     */
    @GetMapping("/getCachedAttendanceData")
    public Object getCachedAttendanceData(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {

        try {
            Object cachedData = attendanceCacheService.getCachedAttendanceData(startDate, endDate);
            if (cachedData != null) {
                return ServiceResult.getSuccessResult(cachedData);
            } else {
                return ServiceResult.getFailureResult("404", "暂无缓存数据");
            }
        } catch (Exception e) {
            return ServiceResult.getFailureResult("500", e.getMessage());
        }
    }

    /**
     * 查询用户考勤记录
     */
    @PostMapping("/getAttendanceList")
    public Object getAttendanceList(@RequestParam List<String> userIdList,
                                    @RequestParam String startDate,
                                    @RequestParam String endDate,
                                    @RequestParam(required = false) Long offset,
                                    @RequestParam(required = false) Long limit) {
        try {
            // 设置默认值
            long defaultLimit = 50L;
            long defaultOffset = 0L;

            // 检查时间跨度是否超过7天，如果超过则分段查询
            List<Object> allResults = new ArrayList<>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdfWithTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            Date start = sdf.parse(startDate);
            Date end = sdf.parse(endDate);

            // 设置开始时间为当天 00:00:00
            Calendar startCal = Calendar.getInstance();
            startCal.setTime(start);
            startCal.set(Calendar.HOUR_OF_DAY, 0);
            startCal.set(Calendar.MINUTE, 0);
            startCal.set(Calendar.SECOND, 0);
            startCal.set(Calendar.MILLISECOND, 0);
            Date startTime = startCal.getTime();

            // 设置结束时间为当天 23:59:59
            Calendar endCal = Calendar.getInstance();
            endCal.setTime(end);
            endCal.set(Calendar.HOUR_OF_DAY, 23);
            endCal.set(Calendar.MINUTE, 59);
            endCal.set(Calendar.SECOND, 59);
            endCal.set(Calendar.MILLISECOND, 999);
            Date endTime = endCal.getTime();

            long diffInDays = (endTime.getTime() - startTime.getTime()) / (1000 * 60 * 60 * 24);

            if (diffInDays > 7 || userIdList.size() > 1) {
                // 如果时间跨度超过7天或者查询多个用户，需要分段查询
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(startTime);

                Date currentStart = startTime;
                while (currentStart.before(endTime) || currentStart.equals(endTime)) {
                    calendar.setTime(currentStart);
                    calendar.add(Calendar.DAY_OF_MONTH, 6); // 加6天，总共7天

                    Date currentEnd = calendar.getTime();
                    if (currentEnd.after(endTime)) {
                        currentEnd = endTime;
                    }

                    // 如果是多个用户，为每个用户单独查询
                    if (userIdList.size() > 1) {
                        for (String userId : userIdList) {
                            List<String> singleUserList = Arrays.asList(userId);
                            Object result = dingTalkUserService.getAttendanceList(
                                    singleUserList,
                                    sdfWithTime.format(currentStart),
                                    sdfWithTime.format(currentEnd),
                                    defaultOffset,
                                    defaultLimit
                            );

                            // 合并结果
                            if (result instanceof List) {
                                allResults.addAll((List<?>) result);
                            }
                        }
                    } else {
                        // 单个用户查询
                        Object result = dingTalkUserService.getAttendanceList(
                                userIdList,
                                sdfWithTime.format(currentStart),
                                sdfWithTime.format(currentEnd),
                                defaultOffset,
                                defaultLimit
                        );

                        // 合并结果
                        if (result instanceof List) {
                            allResults.addAll((List<?>) result);
                        }
                    }

                    // 下一次查询从当前结束日期的第二天开始
                    calendar.setTime(currentEnd);
                    calendar.add(Calendar.DAY_OF_MONTH, 1);
                    currentStart = calendar.getTime();
                }

                // 对合并后的结果按日期排序
                allResults.sort((r1, r2) -> {
                    if (r1 instanceof Map && r2 instanceof Map) {
                        Map<String, Object> map1 = (Map<String, Object>) r1;
                        Map<String, Object> map2 = (Map<String, Object>) r2;
                        String date1 = (String) map1.get("date");
                        String date2 = (String) map2.get("date");
                        return date1 != null && date2 != null ? date1.compareTo(date2) : 0;
                    }
                    return 0;
                });

                return ServiceResult.getSuccessResult(allResults);
            } else {
                // 时间跨度不超过7天且单个用户，直接查询
                return ServiceResult.getSuccessResult(
                        dingTalkUserService.getAttendanceList(
                                userIdList,
                                sdfWithTime.format(startTime),
                                sdfWithTime.format(endTime),
                                offset != null ? offset : defaultOffset,
                                limit != null ? limit : defaultLimit
                        )
                );
            }
        } catch (Exception e) {
            return ServiceResult.getFailureResult("500", e.getMessage());
        }
    }


}
